/**
 * padding zero before numbers that lower than 10
 * @param  {number} input             number to prefix 
 * @return {String}                   zero-prefixed number(as a string)
 */
var zeroPrefix = function(input) {
	return input < 10 ? ('0' + input) : input;
};

/**
 * transform Date object to formatted string
 * @param  {Date} date                  date to format
 * @param  {String} format              given format like 'yyyy/MM/dd'
 * @return {String}                     formatted string
 */
var format = function(date, dateFormat) {
	var splits = dateFormat.split(/[^a-zA-Z]/);
	var	tokenMap = {
		yyyy: date.getFullYear(),
		MM: date.getMonth() + 1,
		dd: date.getDate(),
		hh: date.getHours(),
		mm: date.getMinutes(),
		ss: date.getSeconds()
	};
	var formattedDate = dateFormat;

	splits.forEach(function(token) {
		if (token in tokenMap) {
			var val = zeroPrefix(tokenMap[token]);
			formattedDate = formattedDate.replace(token, val);
		}
	});
	
	return formattedDate;
};

/**
 * transform formatted date string to Date object
 * @param  {String} dateStr              date string to transform
 * @return {Date}                        transformed date object
 */
var toDate = function(dateStr) {
	// date by timestamp (skip yyyyMMdd format)
	if (/^\d{9,}$/.test(dateStr)) {
		return new Date(+dateStr);
	}

	// support yyyy MM dd format
	var formattedDate = dateStr.replace(/\D/g, '');
	
	// current time of 1970-01-01
	var tmp = new Date(Date.now() % 864e5);
	tmp.setFullYear(formattedDate.slice(0, 4));
	tmp.setMonth(+formattedDate.slice(-4, -2) - 1);
	tmp.setDate(formattedDate.slice(-2));

	return tmp;
};

/**
 * compare two dates
 * @param  {Date} dateA
 * @param  {Date} dateB
 * @return {boolean}                 whether the two Dates are the same day
 */
var sameDayWith = function(dateA, dateB) {
	if (typeof dateA !== typeof dateB || !(dateA instanceof Date)) return false;

	var isSameDate = dateA.getDate() === dateB.getDate();
	var isInSameDay = Math.abs(dateA.getTime() - dateB.getTime()) < 864e5;

	return isSameDate && isInSameDay;
};

/**
 * check if the given year is a leap year
 * @param  {number}  year
 * @return {Boolean}
 */
var isLeapYear = function(year) {
	return year % 400 === 0 || (year % 100 !== 0 && year % 4 === 0);
};

/**
 * get every month's days of given year
 * @param  {number} year
 * @return {array}  array of days in every month
 */
var daysEveryMonthOfYear = function(year) {
	return [31, 28 + (isLeapYear(year) ? 1 : 0), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
};

export default {
	isLeapYear,
	daysEveryMonthOfYear,
	format,
	toDate,
	sameDayWith,
}
